local function createChat(context,channel)
    for key, player in pairs(y3.player_group:get_neutral_player_group():pick()) do
        if player:get_state() ~= y3.const.RoleStatus['NONE'] then
            local chat_preb = player:storage_get('chat_preb')
            if not chat_preb then
                return
            end
            
            local chat_list = chat_preb:get_child('root.chat_history')
            ---@cast chat_list UI
            -- local preb = y3.ui_prefab.create(player, "chat_cell", chat_list)
            local ui_root = chat_preb:get_child('root')
            local text_ui = y3.ui.create_ui(player, chat_list, '文本')
            text_ui
                :set_font_size(16)
                :set_text_alignment(y3.const.UIHAlignmentType['左'])
                :set_relative_parent_pos('左侧',0)
                :set_relative_parent_pos('右侧',0)
            
            
            if not player:storage_get('player_' .. channel .. '_history') then
                player:storage_set('player_' .. channel .. '_history', {})
            end
            -- print(player, player:storage_get('channel'))
            local chat_history_table = player:storage_get('player_' .. channel .. '_history')
            chat_history_table[#chat_history_table + 1] = text_ui

            GameAPI.set_text_over_length_handling_type(player.handle, text_ui.handle, true)
            -- local text_ui = preb:get_child('context')
            text_ui:set_ui_comp_parent(chat_list)
            text_ui:set_text(context)
            
            text_ui:set_visible(player:storage_get('channel') == channel)

            if  player:storage_get('channel') == channel then
                chat_preb:get_child('root.input.cur_channel.red_point'):set_visible(false)
            else
                chat_preb:get_child('root.input.cur_channel.red_point'):set_visible(true)
            end
            

            if player:storage_get("聊天输入框定时器1") then
                player:storage_get("聊天输入框定时器1"):remove()
            end
            if player:storage_get("聊天输入框定时器2") then
                player:storage_get("聊天输入框定时器2"):remove()
            end

            GameAPI.stop_eca_anim(player.handle, ui_root.handle, 3)
            ui_root:set_visible(true)
            ui_root:set_alpha(100)
            
            if not player:storage_get('输入框焦点') then
                local t1 = y3.ltimer.wait(20, function (timer, count)
                    ui_root:set_anim_opacity(100,0,1,y3.const.EaseType['ease_in_out曲线'])
                    local t2 = y3.ltimer.wait(1, function (timer, count)
                        ui_root:set_visible(false)
                        ui_root:set_alpha(100)

                    end)
                    player:storage_set('聊天输入框定时器2', t2)
                end)
                player:storage_set('聊天输入框定时器1', t1)
                if ui_root:is_visible() == false then
                    ui_root:set_visible(true)
                end
            end
            y3.ltimer.wait_frame(3, function (timer, count)
                chat_list:set_list_view_percent(100)
            end)
            
        end

    end


end

---接受到全局消息
y3.sync.onSync("chat_received", function (message, source)
    if not message then
        return
    end
    local message_uuid = message.uuid
    if not _G._ReceivedMessages then
        _G._ReceivedMessages = {}
    end

    if not _G._ReceivedMessages[message_uuid] then
        _G._ReceivedMessages[message_uuid] = true
        createChat(message.content, 'all')
    end
end)

---聊天元件初始化
---@param player Player
local function initChatPreb(player)
    local preb = y3.ui_prefab.create(player, "chat", y3.ui.get_ui(player, "GameHUD"))
    preb:get_child("")
        :set_pos(0,540)
    player:storage_set('chat_preb', preb)

    local ui_root = preb:get_child('root')
    local input_ui = preb:get_child('root.input.input_field.context')
    local switch_channel_btn = preb:get_child('root.input.cur_channel')
    local switch_channel_list = preb:get_child('root.input.channels_list')
    local switch_2allchannel_btn = preb:get_child('root.input.channels_list.all')
    local switch_2roomchannel_btn = preb:get_child('root.input.channels_list.room')
    local chat_list = preb:get_child('root.chat_history')

    player:storage_set('channel', 'room')




    local function sendAllMessage(input_text)
        if Client then
            Client:sendChatMessage(input_text)
        end
        
    end

    local function sendRoomMessage(input_text)
        createChat(input_text, 'room')
    end

    
    player:event("本地-界面-输入框获取焦点", input_ui, function (trg, data)

        -- print("输入框获取焦点") 
        player:storage_set('输入框焦点', true)

        if player:storage_get("聊天输入框定时器1") then
            player:storage_get("聊天输入框定时器1"):remove()
        end
        if player:storage_get("聊天输入框定时器2") then
            player:storage_get("聊天输入框定时器2"):remove()
        end

        -- Pos = 0
        -- Rotation = 1
        -- Scale = 2
        -- Opacity = 3
        GameAPI.stop_eca_anim(player.handle, ui_root.handle, 3)
        ui_root:set_visible(true)
        ui_root:set_alpha(100)
    end)

    player:event("本地-界面-输入框失去焦点", input_ui, function (trg, data)
        -- print("输入框失去焦点")
        player:storage_set('输入框焦点', false)
        local t1 = y3.ltimer.wait(20, function (timer, count)
            ui_root:set_anim_opacity(100,0,1,y3.const.EaseType['ease_in_out曲线'])
            local t2 = y3.ltimer.wait(1, function (timer, count)
                ui_root:set_visible(false)
                ui_root:set_alpha(100)

            end)
            player:storage_set('聊天输入框定时器2', t2)
        end)
        player:storage_set('聊天输入框定时器1', t1)
    end)



    --- 回车事件函数
    --- @param player Player
    local function enterFunc(player)
        -- print(math.random(),"回车")
        local preb = player:storage_get('chat_preb')
        local ui_root = preb:get_child('root')
        local input_ui = preb:get_child('root.input.input_field.context')

        local input_text = input_ui:get_input_field_content()
        -- if player:storage_get('输入框焦点') then
        --     if input_text ~= "" then
        --         -- 发送消息
        --         if player:storage_get('channel') == 'all' then
        --             sendAllMessage(input_text)
        --         elseif player:storage_get('channel') == 'room' then
        --             sendRoomMessage(input_text)
        --         end

        --     else
        --         ui_root:set_visible(true)
        --     end
        -- else
        --     if ui_root:is_visible() == false then
        --         ui_root:set_visible(true)
        --     end
        --     input_ui:set_input_field_focus()
        -- end

        if input_text ~= "" then
            -- 发送消息
            if player:storage_get('channel') == 'all' then
                if player == y3.player:get_local() then
                    local time = y3.game.get_current_server_time(8)
                    local input_text = string.format("[%02d:%02d] ", time.hour, time.min) .. GameAPI.get_player_full_nick_name(player.handle) .. ': ' .. input_text
                    sendAllMessage(input_text)
                    input_ui:set_input_field_focus()
                    input_ui:set_text("")
                end

            elseif player:storage_get('channel') == 'room' then
                local time = y3.game.get_current_server_time(8)
                local input_text = string.format("[%02d:%02d] ", time.hour, time.min) .. GameAPI.get_player_full_nick_name(player.handle) .. ': ' .. input_text
                sendRoomMessage(input_text)
                input_ui:set_input_field_focus()
                input_ui:set_text("")
            end

        else
            if ui_root:is_visible() == false then
                ui_root:set_visible(true)
            end
            input_ui:set_input_field_focus()
        end
    end

    player:event("键盘-抬起", y3.const.KeyboardKey['ENTER'], function (trg, data)
        enterFunc(data.player)
    end)

    player:event("键盘-抬起", y3.const.KeyboardKey['NUM_ENTER'], function (trg, data)
        enterFunc(data.player)
    end)



    switch_channel_btn:add_fast_event('左键-点击', function (trg)
        switch_channel_list:set_visible(switch_channel_list:is_visible() == false)
        local chat_preb = player:storage_get('chat_preb')   
        chat_preb:get_child('root.input.cur_channel.red_point'):set_visible(false)
    end)

    switch_2allchannel_btn:add_fast_event('左键-点击', function (trg)
        switch_channel_list:set_visible(false)
        player:storage_set('channel', 'all')
        local preb = player:storage_get('chat_preb')
        local ui_root = preb:get_child('root')
        local input_ui = preb:get_child('root.input.input_field.context')
        local cur_channel_ui = preb:get_child('root.input.cur_channel.str')
        cur_channel_ui:set_text('[世界]')
        input_ui:set_input_field_focus()

        local chat_room_history_table = player:storage_get('player_room_history')
        local chat_all_history_table = player:storage_get('player_all_history')
        if chat_room_history_table then
            for key, value in pairs(chat_room_history_table) do
                ---@cast value UI
                value:set_visible(false)
            end
        end


        if chat_all_history_table then
            for key, value in pairs(chat_all_history_table) do
                ---@cast value UI
                value:set_visible(true)
            end
        end


        if Client then
            
        end

    end)

    switch_2roomchannel_btn:add_fast_event('左键-点击', function (trg)
        switch_channel_list:set_visible(false)
        player:storage_set('channel', 'room')
        local preb = player:storage_get('chat_preb')
        local ui_root = preb:get_child('root')
        local input_ui = preb:get_child('root.input.input_field.context')
        local cur_channel_ui = preb:get_child('root.input.cur_channel.str')
        cur_channel_ui:set_text('[房间]')
        input_ui:set_input_field_focus()

        local chat_room_history_table = player:storage_get('player_room_history')
        local chat_all_history_table = player:storage_get('player_all_history')

        if chat_room_history_table then
            for key, value in pairs(chat_room_history_table) do
                ---@cast value UI
                value:set_visible(true)
            end
        end


        if chat_all_history_table then
            for key, value in pairs(chat_all_history_table) do
                ---@cast value UI
                value:set_visible(false)
            end
        end
        if Client then
            
        end
    end)


end



y3.game:event("游戏-初始化", function (trg, data)
    local players = y3.player_group:get_neutral_player_group():pick()
    for key, player in pairs(players) do
        if player:get_state() ~= y3.const.RoleStatus['NONE'] then
            initChatPreb(player)
        end
    end
end)